<template>
	<view class="page page-primary page-goods">
		<page-header theme="colorful"></page-header>
		<view class="page-content">
			<page-statistic :data="userType === '2' ? statisticData2 : statisticData1"></page-statistic>
			<view class="page-search">
				<fui-input v-model="searchValue" borderTop color="#333" radius="16" :borderBottom="false" placeholderStyle="font-size:28rpx"
					placeholder="请输入商品名称"></fui-input>
				<span class="icon iconfont" @click="searchCenter">&#xe628;</span>
			</view>

			<!-- 标签项 -->
			<view class="">
				<!-- //供应链是1 供应商是2 -->
				<view class="" style="margin-top: 40rpx;" v-if="userType == 1">
<!-- 					<view class="page-parent-tab">
						<fui-tabs :tabs="parentTabs" @change="onChangeParentTab" background="rgba(0,0,0,0)" size="32"
							color="#666666" sliderRadius="-1" :center="true" fontWeight="bold" selectedSize="32"
							selectedColor="var(--fui-color-primary)" scale="1" sliderHeight="8" selectedFontWeight="bold"
							bottom="3"></fui-tabs>
						<fui-button class="ui-btn-primary_plain" text="新品上架" width="126rpx" height="48rpx" radius="8rpx" size="24" @click="jumpNewRelease">
            </fui-button>
					</view> -->
					<view class="page-child-tab">
						<text class="child-tab-item" :class="{ active: index === curChildTab }"
							v-show="item.parent === curParentTab || item.parent === 'all'"
							v-for="(item, index) in childTabs" :key="item.name" @click="onChangeChildTab(index)">
							{{ item.name }}
              <text v-show="item.badge > 0" class="subscript">{{ item.badge }}</text>
						</text>
					</view>
				</view>

				<view class="page-parent-tab supplier-tab" v-else>
					<fui-tabs :tabs="supplierTabs" @change="onChangeSupplierTab" background="rgba(0,0,0,0)" size="26"
						color="#666666" sliderRadius="-1" :center="true" fontWeight="bold" selectedSize="26"
						selectedColor="var(--fui-color-primary)" scale="1" :height='75' sliderHeight="8" selectedFontWeight="bold"
						bottom="2"></fui-tabs>
					<view class="">
						<fui-button class="ui-btn-primary_plain" text="新品上架" width="126rpx" height="48rpx" radius="8rpx"
							size="24" @click="jumpNewRelease"></fui-button>
					</view>

				</view>
				<view class="">

				</view>
			</view>

			<!-- 商品列表 -->
			<view class="shop-list">
				<view class="shop-item" v-for="item in listData" :key="item.id"
					@click="jumpDetail(item.id, item.status)">
					<image :src="item.sliderPicUrls[0]"
						style="width: 164rpx; height: 164rpx;backgroundColor: antiquewhite; border-radius: 16rpx; overflow: hidden" mode="aspectFill">
					</image>
					<view class="shop-item-right">
						<view class="right-title"><view class="supplier-tag" v-if="userType == 1 && item.isSelfManage === 'Y'">自营</view>{{ item.title }}</view>
						<view class="right-list">
							<view class="right-text" style="width: 100%" v-if="curParentTab">
								<image src="/static/images/icon-gys.png" style="width: 24rpx; height: 22rpx">
								</image>
								{{ item.supplier }}
							</view>
							<view v-show="(curChildTab < 3) && (curSupplierTab < 3)" class="right-text" style="width: 100%">
								<image src="/static/images/icon-kc.png" style="width: 22rpx; height: 22rpx"></image>
								库存
								<span class="right-number">{{ item.inventory }}</span>
								<span>{{ item.invUnit }}</span>
							</view>
							<view class="right-text" style="width: 100%">
								<image src="/static/images/iocn-dj.png" style="width: 26rpx; height: 26rpx"></image>
								单价
								<span class="right-number">{{ utils.moneyFormatter(item.qgjg / 100)}}</span>
								<span>{{ item.prUnit }}</span>
							</view>
							<view class="right-text" style="width: 100%">
								<image src="/static/images/icon-qssl.png" style="width: 24rpx; height: 22rpx">
								</image>
								起售数量
								<span class="right-number">{{ item.qgsl }}</span>
								<span>{{ item.saleUnit }}</span>
							</view>
						</view>
					</view>
				</view>
			</view>
			<fui-loadmore :state="moreState"></fui-loadmore>
		</view>
    <!-- //供应链是1 供应商是2 -->
		<fui-fab class="ui-float-btn" distance="36" @click="jumpAddGoods" v-if="userType == 2">
			<fui-text size="24" color="#fff">
				新增
				<br />
				商品
			</fui-text>
		</fui-fab>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		inject,
		watch
	} from 'vue';
	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh,
		onShow
	} from '@dcloudio/uni-app';
	import pageHeader from '@/components/header';
	import pageStatistic from '@/components/statistic';
	import supplierApi from '@/api/supplier';
	import goodsApi from '@/api/goods';
	import utils from '@/components/firstui/fui-utils'
	import { useStore	} from 'vuex';
  import { formatValue, formatUnit } from '@/utils/tools'
	const store = useStore();

	const tab = inject('$tab');
	const modal = inject('$modal');

	// 用户类型：1-供应链，2-供应商
	const { userType, companyId } = store.getters

	// 列表底部加载状态，可选值：1-上拉加载 2-正在加载... 3-没有更多了
	const moreState = ref(1);

	// 新增商品
	const jumpAddGoods = () => {
		tab.navigateTo('/pages/goods/addGoods');
	};

	// 一级标签页
	// const parentTabs = ref(['自营商品', '直供商品']);
  const parentTabs = ref(['直供商品']);
	const curParentTab = ref(userType === '1' ? 1 : 0);
	const onChangeParentTab = (e) => {
		curParentTab.value = e.index;
		curChildTab.value = 0; //一级标签改变时，二级标签为0
	};

	// 二级标签页--供应链
	const childTabs = ref([{
			name: '已上架',
			parent: 'all'
		},
		{
			name: '待审核',
			parent: 1,
      isDot: true,
      badge: 0
		},
		{
			name: '已驳回',
			parent: 1,
      isDot: true,
      badge: 0
		},
		{
			name: '已下架',
			parent: 'all'
		},
		{
			name: '商品目录',
			parent: 0
		}
	]);

	// 二级标签页--供应商
	const supplierTabs = ref([{
			name: '已上架',
		},
		{
			name: '审核中',
      isDot: true,
      badge: 0
		},
		{
			name: '已驳回',
      isDot: true,
      badge: 0
		},
		{
			name: '已下架',
		},
		{
			name: '商品目录',
		}
	]);

	const curSupplierTab = ref(0); //当前标签页--供应商
	const onChangeSupplierTab = (e) => {
		curSupplierTab.value = e.index;
	};

	// 当前二级标签
	const curChildTab = ref(0);
	const onChangeChildTab = (index) => {
		curChildTab.value = index;
	};

	// 商品列表
	const listData = ref([]);

	// 详情
	const jumpDetail = (id, status) => {
		tab.navigateTo(
			`/pages/goods/detail?id=${id}&curParentTab=${curParentTab.value}&curChildTab=${curChildTab.value}&curSupplierTab=${curSupplierTab.value}`
		);
	};
	// 新品上架
	const jumpNewRelease = () => {
		uni.navigateTo({
			url: `/pages/goods/newRelease?isDetail=false`
		});
	};

	const pagination = ref({
		pageNo: 1,
		pageSize: 10
	})

	const directQueryData = ref({
		tabType: 0, //查询类型0上架 1下架 5审核 6全部
		name: '' //查询商品名称
	});

	const selfQueryData = ref({
		tabType: 0, // 0=上架，1=下架，5=审核中，6=全部，7=可上架商品，8=已驳回
		name: '' //查询商品名称
	});

	const setSelfQueryData = ({
		pageNo = 1,
		pageSize = 10,
		tabType = 0,
		name = ''
	}) => {
		selfQueryData.value = {
			pageNo,
			pageSize,
			tabType, // 0=上架，1=下架，5=审核中，6=全部，7=可上架商品，8=已驳回
			name //查询商品名称
		};
	};

	const setDirectQueryData = ({
		pageNo = 1,
		pageSize = 10,
		tabType = 0,
		name = ''
	}) => {
		directQueryData.value = {
			pageNo,
			pageSize,
			tabType, //查询类型0上架 1下架 5审核 6全部
			name //查询商品名称
		};
	};

	// 直供商品列表
	const getDirectSupply = () => {
		try {
			setDirectQueryData({
				...directQueryData.value,
				...pagination.value,
			})
			goodsApi.getSpuTenantPage({
				...directQueryData.value,
				name: searchValue.value,
				supplierId: companyId
			}).then((res) => {
				modal.closeLoading();
				uni.stopPullDownRefresh(); //终止下拉刷新动作
				if (res.code === 0) {
					if (pagination.value.pageNo * pagination.value.pageSize >= res.data.total) {
						moreState.value = 3; // 列表底部加载状态，可选值：1-上拉加载 2-正在加载... 3-没有更多了
					} else {
						moreState.value = 1;
					}
					const newData = res.data.list.map((item) => {
						return {
							...item,
							title: item.name,
							imgUrl: item.picUrl,
							inventory: item.stock,
							invUnit: item.unit,
							prUnit: `元/${item.unit}`,
							sale: item.prices,
							saleUnit: item.unit,
							price: item.price / 100,
							supplier: item.deptName
						};
					});
					listData.value = [...listData.value, ...newData]
				} else {
					modal.msgError(res.msg);
				}
			});
		} catch (e) {
			modal.closeLoading();
		}
	};

	// 供应商及供应链自营商品列表
	const getSelfSupport = () => {
		try {
			setSelfQueryData({
				...selfQueryData.value,
				...pagination.value,
			})
			goodsApi.getProductList({
				...selfQueryData.value,
				name: searchValue.value,
				supplierId: companyId
			}).then((res) => {
				uni.stopPullDownRefresh(); //终止下拉刷新动作
				modal.closeLoading();
				if (res.code === 0) {
					if (pagination.value.pageNo * pagination.value.pageSize >= res.data.total) {
						moreState.value = 3;
					} else {
						moreState.value = 1;
					}
					const newData = res.data.list.map((item) => {
						return {
							...item,
							title: item.name,
							imgUrl: item.picUrl,
							inventory: item.stock,
							invUnit: item.unit,
							prUnit: `元/${item.unit}`,
							sale: item.prices,
							saleUnit: item.unit,
							price: item.price / 100
						};
					});
					listData.value = [...listData.value, ...newData]
				} else {
					modal.msgError(res.msg);
				}
			});
		} catch (e) {
			modal.closeLoading();
		}
	};

	const { currentTenantId, currentDeptId } = store.getters
	const statisticData1 = ref([
		{ name: '商品数量', value: 0, unit: '个' },
		{ name: '直供商品', value: 0, unit: '个' },
		{ name: '订单数量', value: 0, unit: '单' }
	]);
  const statisticData2 = ref([
		{ name: '商品数量', value: 0, unit: '个' },
		{ name: '订单数量', value: 0, unit: '单' }
	]);
  const getStatisticsData = () => {
    try {
      supplierApi.getHomeData({
				zhid: currentTenantId,
				gsid: currentDeptId,
				yhlx: userType
			}).then(res => {
        if (res.code === 0 && res.data) {
          if (userType === '2') {
            if (res.data.sptjxx[0]) {
							statisticData2.value[0].value = formatValue(res.data.sptjxx[0].val01)
							statisticData2.value[0].unit = formatUnit(res.data.sptjxx[0].val01, '个')
            }
            if (res.data.ddtjxx[0]) {
							statisticData2.value[1].value = formatValue(res.data.ddtjxx[0].val02)
							statisticData2.value[1].unit = formatUnit(res.data.ddtjxx[0].val02, '单')
            }
          } else {
            if (res.data.sptjxx[0]) {
							statisticData1.value[0].value = formatValue(res.data.sptjxx[0].val01)
							statisticData1.value[0].unit = formatUnit(res.data.sptjxx[0].val01, '个')
							statisticData1.value[1].value = formatValue(res.data.sptjxx[0].val04)
							statisticData1.value[1].unit = formatUnit(res.data.sptjxx[0].val04, '个')
            }
            if (res.data.ddtjxx[0]) {
							statisticData1.value[2].value = formatValue(res.data.ddtjxx[0].val02)
							statisticData1.value[2].unit = formatUnit(res.data.ddtjxx[0].val02, '单')
            }
          }
        } else {
          modal.msgError('获取统计数据失败！')
        }
      })
    } catch(err) {
      modal.msgError('获取统计数据失败！')
    }
  }

	// 标签页统计数据
	const getGoodsStatList = () => {
    try {
      goodsApi.getGoodsStatList(userType === '2' ? companyId : '').then(res => {
        if (res.code === 0 && res.data) {
					if (userType === '2') {
						// 获取商品待审核、已驳回的角标数
						supplierTabs.value[1].badge = res.data.shzCount
						supplierTabs.value[2].badge = res.data.ybhCount
					} else {
						// 获取商品待审核、已驳回的角标数
						childTabs.value[1].badge = res.data.shzCount
						childTabs.value[2].badge = res.data.ybhCount
					}
        } else {
          modal.msgError('获取统计数据失败！')
        }
      })
    } catch(err) {
      modal.msgError('获取统计数据失败！')
    }
  }

  onShow(() => {
    getStatisticsData()
    getGoodsStatList()
		initListData()
  })

	// 监听当前一级，请求数据  ---供应链
	watch(
		curParentTab,
		(data) => {
			if (data === 0) {
				setSelfQueryData({
					name: selfQueryData.value.name
				});
				getSelfSupport();
			} else {
				setDirectQueryData({
					name: directQueryData.value.name
				});
				getDirectSupply();
			}
		}, {
			immediate: true
		}
	);

	// 监听一、二级标签变化,一级标签变化不请求参数，否则会重复请求  ---供应链
	watch([curParentTab, curChildTab], ([newParentTab, newChildTab], [oldParentTab, oldChildTab]) => {
		modal.loading('加载中...');
		moreState.value = 2;
		listData.value = []; //清空数据
		pagination.value.pageNo = 1;

		switch (newChildTab) {
			case 0:
				setSelfQueryData({
					tabType: 0, // 0=上架，1=下架，5=审核中，6=全部，7=可上架商品，8=已驳回
					name: selfQueryData.value.name
				});
				setDirectQueryData({
					tabType: 0, //查询类型 0上架 1下架 5审核 6全部
					name: directQueryData.value.name
				});
				break;
			case 1:
				setDirectQueryData({
					tabType: 5,
					name: directQueryData.value.name
				});
				break;
			case 2:
				setSelfQueryData({
					tabType: 1,
					name: selfQueryData.value.name
				});
				setDirectQueryData({
					tabType: 8,
					name: directQueryData.value.name
				});
				break;
			case 3:
				setSelfQueryData({
					tabType: 1,
					name: selfQueryData.value.name
				});
				setDirectQueryData({
					tabType: 1,
					name: directQueryData.value.name
				});
				break;
			default:
				setSelfQueryData({
					tabType: 6,
					name: selfQueryData.value.name
				});
				break;
		}

		if (newParentTab === oldParentTab) {
			if (curParentTab.value === 0) {
				getSelfSupport();
			} else {
				getDirectSupply();
			}
		}
	});

	// 监听标签变化 ----供应商
	watch(
		curSupplierTab,
		(data) => {
			modal.loading('加载中...');
			moreState.value = 2;
			listData.value = []; //清空数据
			pagination.value.pageNo = 1;
			switch (data) {
				case 0:
					setSelfQueryData({
						tabType: 0, // 0=上架，1=下架，5=审核中，6=全部，7=可上架商品，8=已驳回
						name: selfQueryData.value.name
					});
					break;
				case 1:
					setSelfQueryData({
						tabType: 5,
						name: selfQueryData.value.name
					});
					break;
				case 2:
					setSelfQueryData({
						tabType: 8,
						name: selfQueryData.value.name
					});
					break;
				case 3:
					setSelfQueryData({
						tabType: 1,
						name: selfQueryData.value.name
					});
					break;
				default:
					setSelfQueryData({
						tabType: 6,
						name: selfQueryData.value.name
					});
					break;
			}

			getSelfSupport();
		}
	);

	// 上拉加载更多
	onReachBottom(() => {
		if (moreState.value == 1) {
			pagination.value.pageNo++
			modal.loading('加载中...');
			moreState.value = 2;
			if (curParentTab.value === 0) {
				getSelfSupport();
			} else {
				getDirectSupply();
			}
		}
	});


	// 下拉刷新
	onPullDownRefresh(() => {
		initListData();
	});

	const initListData = () => {
		listData.value = [];
		pagination.value.pageNo = 1;
		//供应链是1 供应商是2
		if (userType == 2 || curParentTab.value === 0) {
			getSelfSupport();
		} else {
			getDirectSupply();
		}
	}


	// 搜索
	const searchValue = ref('')
	const searchCenter = () => {
		setSelfQueryData({
			tabType: selfQueryData.value.tabType,
			name: searchValue.value
		});
		setDirectQueryData({
			tabType: directQueryData.value.tabType,
			name: searchValue.value
		});
		listData.value = []; //清空数据
		if (userType == 2 || curParentTab.value === 0) {
			getSelfSupport();
		} else {
			getDirectSupply();
		}
	};



	// 监听refreshFlag，新增，新品上架后刷新列表
	watch(
		() => store.getters.refreshFlag,
		() => {
			initListData();
		},
	);
</script>

<style lang="scss" scoped>
	.page-goods {
		.page-search {
			position: relative;
			width: 100%;
			margin: 30rpx 0 0;

			:deep(.fui-input__wrap) {
				padding: 20rpx 24rpx !important;
			}

			span {
				position: absolute;
				z-index: 10;
				right: 0;
				top: 0;
				font-size: 1.25rem;
				color: var(--fui-color-link);
				display: inline-block;
				width: 40px;
				height: 40px;
				line-height: 40px;
				text-align: center;
				font-size: 40rpx;
				color: var(--fui-color-link);
			}
		}

		.page-parent-tab {
			position: relative;
			margin-bottom: 30rpx;

			:deep(.fui-tabs__scrollbox) {
				width: fit-content;
			}

			:deep(.fui-tabs__line-short) {
				width: 64rpx !important;
			}

			:deep(.fui-tabs__item) {
				padding-left: 5rpx;
				padding-right: 72rpx;
			}

			::v-deep .ui-btn-primary_plain {
				position: absolute;
				top: 50%;
				right: 0;
				transform: translateY(-50%);

				.fui-button {
					background-color: #ecf4ff !important;
					font-weight: bold;
				}
			}
		}

		.page-child-tab {
			display: flex;
			padding-bottom: 28rpx;

			.child-tab-item {
				height: 48rpx;
				border-radius: 8rpx;
				background: #fff;
				margin-right: 30rpx;
				padding: 0 18rpx;
				line-height: 48rpx;
				white-space: nowrap;
				font-size: 24rpx;
				color: #666666;
        position: relative;

				&.active {
					background: #ecf4ff;
					border: 2rpx solid var(--fui-color-primary);
					font-weight: bold;
					color: var(--fui-color-primary);
				}
        .subscript{
          width: 28rpx;
          height: 28rpx;
          position: absolute;
          top: -4rpx;
          right: -8rpx;
          background: #fb4545;
          border-radius: 100%;
          color: #fff;
          font-size: 16rpx;
          line-height: 28rpx;
          text-align: center;
        }
			}
		}

		.shop-list {
			padding-bottom: 15rpx;

			.shop-item {
				width: 100%;
				background: #ffffff;
				border-radius: 16rpx;
				padding: 28rpx;
				box-sizing: border-box;
				margin-bottom: 30rpx;
				display: flex;

				.shop-item-right {
					margin-left: 24rpx;
					width: calc(100% - 188rpx);

					.right-title {
						font-size: 28rpx;
						font-weight: bold;
						color: #333333;
						margin-bottom: 16rpx;
						.supplier-tag {
							display: inline;
							height: 32rpx;
							background-color: #f95a5a;
							border-radius: 8rpx;
							margin-right: 5rpx;
							padding: 2rpx 10rpx;
							line-height: 32rpx;
							font-size: 20rpx;
							font-weight: normal;
							color: #fff;
						}
					}

					.right-list {
						display: flex;
						flex-wrap: wrap;

						.right-text {
							width: 50%;
							font-size: 24rpx;
							font-weight: 400;
							color: #999999;
							display: flex;
							align-items: center;
							margin-bottom: 10rpx;

							image {
								padding-right: 10rpx;
							}

							span {
								color: #333333;
							}

							.right-number {
								font-weight: bold;
								color: var(--fui-color-link);
								padding: 0 10rpx;
							}
						}
					}
				}
			}
		}

		.ui-float-btn {
			::v-deep .fui-fab__btn-inner {
				font-size: 24rpx;
				color: #fff;
				letter-spacing: 4rpx;
			}
		}

		.supplier-tab {
			margin-top: 30rpx;

			:deep(.fui-tabs__item) {
				padding-left: 5rpx;
				padding-right: 25rpx;
			}
		}
	}
</style>